package com.violet.gateway.error;

import com.violet.common.exception.IdentityInfoExpiredException;
import com.violet.gateway.utils.WebfluxResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.naming.NoPermissionException;


/**
 * 类说明: Gateway网关统一异常处理
 *
 * @author wqf
 * @date 2022/5/25 17:54
 */

@Order(-1)
@Configuration
public class GlobalErrorExceptionHandler implements ErrorWebExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalErrorExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.error("=================网关异常=================", ex);
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        // 设置返回JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        String errorMsg = ex.getMessage();
        if (ex instanceof ResponseStatusException) {
            status = ((ResponseStatusException) ex).getStatus();
        }
        if (ex instanceof IdentityInfoExpiredException) {
            status = HttpStatus.UNAUTHORIZED;
            errorMsg = "身份信息已失效";
        }
        if (ex instanceof NoPermissionException) {
            status = HttpStatus.FORBIDDEN;
            errorMsg = "暂无权限";
        }
        if (ex instanceof InvalidTokenException) {
            errorMsg = "token校验不通过";
        }
        return WebfluxResponseUtil.responseFailed(exchange, status, errorMsg);
    }
}